﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using bmapi.HelperClass;
using bmapi.Models.DataEntity;
using bmapi.SQLServerAccess;
using static bmapi.Models.ShowModel;

namespace bmapi.Controllers
{
    public class DetailController : PageController
    {
        #region 样板详情 
        // GET: api/Detail
        /// <summary>
        /// 样板详情
        /// </summary>
        /// <param name="ModelName"></param>
        [HttpGet,Route("styleDetail")]
        public HttpResponseMessage GetModelDetail(string ModelName)
        {
            string sql = "";
            //获取 图片 服装分类名 客户/品牌 创建时间 这个记录只有一条
            sql = "select id as ModelId,image,type,brand,time from Model_tb,Style_tb where Model_tb.style_id=Style_tb.style_id and Model_tb.name=@name";
            try
            {
                SQLCommand sc = new SQLCommand(sql, "@name", ModelName);
                DataTable dt = sc.ExecuteScalars();
                List<ModelInfo> modelinfo = AssistFun.DataTableToList<ModelInfo>(dt);
                if (modelinfo.Count > 0)
                    return AssistFun.toJson(new { status = 200, tip = "成功", data = new { total = 1, rows = modelinfo } });
                else
                    return AssistFun.toJson(new { status = 201, tip = "暂时没有样板详细", data = "" });
            }
            catch (Exception e)
            {
                return AssistFun.toJson(new { status = 201, tip = e.Message, data = "" });
            }            
        }
        #endregion

        #region 款式查询
        //款式查询  
        [HttpGet,Route("style")]
        public HttpResponseMessage SelectStyle(int page = 1, int limit = 15, string ModelName = null, string brand = null, string type = null, DateTime? sTime = null, DateTime? eTime = null)
        {
            string sql = "";
            SQLCommand sc = null;
            if (ModelName != null)
            {
                //判断是否是样板名
                sc = new SQLCommand("select id from Model_tb where name=@name", "@name", ModelName);
                if (sc.ExecuteScalar() != null)
                {
                    sql = " and Model_tb.name='" + ModelName+"'";
                }
                else
                {
                    sql = " and Style_tb.name='" + ModelName+"'";
                }
                sql +=  PingJieCmdForStyle(brand, type, sTime, eTime);
            }
            else
            {
                sql += PingJieCmdForStyle(brand, type, sTime, eTime);
            }
            int totalPage = 0;
            int totalRow = 0;
            string tables = "Style_tb join Model_tb on Style_tb.style_id=Model_tb.style_id";
            string fileds = "Style_tb.name as StyleName,Model_tb.name as ModelName,brand,type,time,state";
            try
            {
                DataTable dt = SQLCommand.GetDataListByPage(tables, fileds, "time desc", sql, limit, page, out totalPage, out totalRow);
                List<StyleInfo> styleinfo = AssistFun.DataTableToList<StyleInfo>(dt);
                if (styleinfo.Count > 0)
                    return AssistFun.toJson(new { status = 200, tip = "成功", data = new { total = totalRow, rows = styleinfo } });
                else
                    return AssistFun.toJson(new { status = 201, tip = "暂时没有款式信息", data = "" });
            }
            catch (Exception e)
            {
                return AssistFun.toJson(new { status = 201, tip = e.Message, data = "" });
            }

        }
        private string PingJieCmdForStyle(string brand,string type,DateTime? sTime=null,DateTime? eTime=null)
        {
            string sql = "";
            if (brand != null )
                sql +=  "and brand='" + brand + "'";
            if (type != null )
                sql +="and type='" + type + "'";
            if (sTime != null)
                sql +=  "and time>='" + sTime+"'" ;
            if (eTime != null)
                sql +=  "and time<='" + eTime+"'" ;
            return sql;
        }
        #endregion

        #region  生产单查询
        //生产单查询  
        [HttpGet,Route("orderSearch")]
        public HttpResponseMessage SelectProductOrder(int page=1,int limit=15,string ModelName = null, string OrderId = null, string ErpName = null, DateTime? sTime = null, DateTime? eTime = null,int Yield = -1,string State=null,string IsBind=null)
        {
            int loginid = GetCrrentIDByToken();
            if (loginid==0)
                return AssistFun.toJson(new { status = 201, tip = "不存在工号0", data = "" });
            User user = GetUserByLoginID(loginid);
            string table = "Order_tb join Model_tb on Model_tb.id=Order_tb.o_model_id";
            string fields = "Order_tb.name as OrderId,Model_tb.name as ModelName,erp_name as ErpName,creater_time as Time,number as Yield,bed,Order_tb.state as State,o_model_id as ModelId,Order_tb.id as Id,Order_tb.bind_id as BindId";
            string sqlwhere = PingJieCmdForOrder(user.PLID,ModelName, OrderId, ErpName, sTime, eTime, Yield,State,IsBind);
            int totalPage, totalRows;
            try
            {
                DataTable dt = SQLCommand.GetDataListByPage(table, fields, "Order_tb.bind_id desc", sqlwhere, limit, page, out totalPage, out totalRows);
                List<ProductInfo> producs = AssistFun.DataTableToList<ProductInfo>(dt);
                if (producs.Count > 0)
                    return AssistFun.toJson(new { status = 200, tip = "成功", data = new { total = totalRows, rows = producs } });
                else
                    return AssistFun.toJson(new { status = 201, tip = "暂时没有生产单信息", data = "" });
            }
            catch (Exception e)
            {
                return AssistFun.toJson(new { status = 201, tip = e.Message, data = "" });
            }
        }
        private string PingJieCmdForOrder(int plid,string modelname, string OrderId, string brand=null, DateTime? sTime = null, DateTime? eTime = null,int yield = -1, string State=null,string IsBind=null)
        {
            string sql = "";
            if (plid > 0)
                sql += " and Order_tb.o_PLID=" + plid;
            if (modelname != null)
                sql +=  " and Model_tb.name='" + modelname+"'";
            if (OrderId != null)
                sql +=  " and Order_tb.name='" + OrderId+"'";
            if (brand != null )
                sql +=  " and erp_name='" + brand + "'";
            if (sTime != null)
                sql +=  " and creater_time>='" + sTime+"'" ;
            if (eTime != null)
                sql +=  " and creater_time<='" + eTime+"'" ;
            if (yield > 0)
                sql += " and number>="+ yield;
            if (State != null)
            {
                if (Convert.ToInt32(State) == 1)
                    sql +=  " and GETDATE()<finish_time and Order_tb.state=1";
                if (Convert.ToInt32(State) == 3)
                    sql +=  " and GETDATE()>finish_time and Order_tb.state=1";
                if (Convert.ToInt32(State) == 0)
                    sql +=  " and Order_tb.state=0";
                if (Convert.ToInt32(State) == 2)
                    sql +=  " and Order_tb.state=2";
            }
            if (IsBind!=null)
            {
                if (Convert.ToInt32(IsBind) == 0)
                {
                    sql += sql + " and Order_tb.bind_id=0";
                }
                else
                {
                    sql += sql + "and Order_tb.bind_id !=0";
                }
            }
           
            return sql;
        }

        #endregion

        #region  生产单细节
        //床信息    
        /// <summary>
        /// 
        /// </summary>
        /// <param name="OrderId">生产单号</param>
        /// <returns></returns>
        [HttpGet,Route("bedinfo")]
        public HttpResponseMessage SelectBedInfo(string Id)
        {
            try
            {
                string sql = "select name as BedName,material_name as MaterialName,lay_len as LayLen,lay_count as LayCount,cut_len as UC from Bed_tb where state=1 and order_id=@orderno";
                SQLCommand sc = new SQLCommand(sql, "orderno", Id);
                DataTable dt = sc.ExecuteScalars();
                List<BedInfo> bedInfo = new List<BedInfo>();
                if (dt != null)
                {
                    bedInfo = AssistFun.DataTableToList<BedInfo>(dt);
                }
                if (bedInfo.Count > 0)
                    return AssistFun.toJson(new { status = 200, tip = "成功", data = new { total = 1, rows = bedInfo } });
                else
                    return AssistFun.toJson(new { status = 201, tip = "没有床信息", data = "" });
            }
            catch (Exception e)
            {
                return AssistFun.toJson(new {status=201,tip=e.Message,data="" });
            }            
        }       
        /// <summary>
        /// 工序列表 工序名  执行人  时间  
        /// </summary>
        /// <param name="modelid">生产单详情时表示Order表中的ID,款式查询时表示model表中的id</param>
        /// <returns></returns>
        [HttpGet,Route("styleDetailProcess")]
        public HttpResponseMessage GetProcessList(string ModelId)
        {
            
            string sql = "select Task_tb.code,name,time from Task_tb,User_tb where Task_tb.code=User_tb.code and Task_tb.id=" + ModelId;
            SQLCommand sc = new SQLCommand(sql);
            try
            {
                DataTable codeInfo = sc.ExecuteScalars();
                if (codeInfo != null)
                {
                    //循环匹对出工序名  
                    List<int> proCode = new List<int>();
                    foreach (DataRow dr in codeInfo.Rows)
                    {
                        proCode.Add(Convert.ToInt32(dr["code"]));
                    }
                    //工序名  
                    List<string> proName = MatchProNameByProCode(proCode);
                    //工序列表 
                    List<ProcessList> proList = new List<ProcessList>();
                    for (int i = 0; i < proName.Count; i++)
                    {
                        ProcessList pro = new ProcessList()
                        {
                            ProcessName = proName[i],
                            UserName = codeInfo.Rows[i]["name"].ToString(),
                            CreateTime = Convert.ToDateTime(codeInfo.Rows[i]["time"])
                        };
                        proList.Add(pro);
                    }
                    if (proList.Count > 0)
                        return AssistFun.toJson(new { status = 200, tip = "成功", data = new { total = proList.Count, rows = proList } });
                    else
                        return AssistFun.toJson(new { status = 201, tip = "暂时没有信息", data = "" });
                }
                else
                    return AssistFun.toJson(new { status = 201, tip = "暂时没有信息", data = "" });
            }
            catch (Exception e)
            {
                return AssistFun.toJson(new { status = 201, tip = e.Message, data = "" });
            }
            
        }
        #endregion

        #region 生产单绑定
        [HttpPut, Route("binding")]
        public HttpResponseMessage Binding(string[] orderId)
        {
            if (orderId.Length > 1)
            {
                SQLCommand sc = new SQLCommand("SELECT MAX(bind_id) FROM Order_tb");
                string maxOrderId = sc.ExecuteScalar();
                int count = 0;
                List<SQLCommand> cmds = new List<SQLCommand>();
                string sql = "";
                for (int i = 0; i < orderId.Length; i++)
                {
                    sc = new SQLCommand("SELECT state,bind_id FROM Order_tb where name= '" + orderId[i] + "'");
                    DataTable bind = sc.ExecuteScalars();
                    int first = Int32.Parse((bind.Rows[0][0]).ToString());
                    int second = Int32.Parse((bind.Rows[0][1]).ToString());
                    if (first == 1)
                    {
                        if (second == 0)
                        {
                            sql = "UPDATE Order_tb SET bind_id=@bindid WHERE name=@name";
                            sc = new SQLCommand(sql);
                            sc.Add("@bindid", Convert.ToInt32(maxOrderId) + 1);
                            sc.Add("@name", orderId[i]);

                            cmds.Add(sc);
                        }
                        else
                        {
                            return AssistFun.toJson(new RespondModel(201, "所选对象已经绑定"));
                        }
                    }
                    else
                    {
                        return AssistFun.toJson(new RespondModel(201, "所选对象已经废弃或已完成"));
                    }
                }
                count = SQLCommand.ExecTran(cmds);
                if (count > 0)
                {
                    return AssistFun.toJson(new RespondModel(200, "修改成功"));
                }
                else
                {
                    return AssistFun.toJson(new RespondModel(201, "修改失败"));
                }
            }
            else
            {
                return AssistFun.toJson(new RespondModel(201, "缺少绑定对象"));
            }

        }
        #endregion

        #region 生产单解除绑定
        [HttpPut, Route("removebinding")]
        public HttpResponseMessage RemoveBinding(string[] bindId)
        {
            int count = 0;
            List<SQLCommand> cmds = new List<SQLCommand>();
            SQLCommand sc = null;
            for (int i = 0; i < bindId.Length; i++)
            {
                if (Convert.ToInt32(bindId[i]) != 0)
                {
                    string sql = "UPDATE Order_tb SET bind_id=0 WHERE bind_id=@bindid";
                    sc = new SQLCommand(sql, "@bindid", bindId[i]);
                    cmds.Add(sc);                   
                }
                else
                {
                    return AssistFun.toJson(new RespondModel(201, "选定对象未绑定"));
                }

            }
            count = SQLCommand.ExecTran(cmds);
            if (count > 0)
            {
                return AssistFun.toJson(new RespondModel(200, "修改成功"));
            }
            else
            {
                return AssistFun.toJson(new RespondModel(201, "修改失败"));
            }
        }
        #endregion
    }
}
